package com.client1.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import com.client1.util.ConfigUtil;
import com.client1.util.HttpUtils;
import com.client1.util.StringUtil;
@Component
public class FilterUtil implements Filter {

	HttpServletRequest req;
	HttpServletResponse resp;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		req = (HttpServletRequest) request;
		resp = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		//是否有局部会话信息
		String isLogin = (String)session.getAttribute("isLogin");
		if (StringUtil.isNotBlank(isLogin)&&ConfigUtil.T_SET.contains(isLogin)) {
			//有局部会话，直接放行
			chain.doFilter(request, response);
			return;
		}
		//地址栏是否有token
		String token = req.getParameter("token");
		if (StringUtil.isNotBlank(token)) {
			//有token判断是否为认证中心token
//			Map<String, String> map= new HashMap<String, String>();
//			map.put("token",token);
			String body = HttpUtils.connect(ConfigUtil.CHECKTICKETURL+"?token="+token).setMethod("GET").setCharset("UTF-8").execute().getBody();
			if (StringUtil.isNotBlank(body)&&body.equals("true")) {
				//token有效，创建局部会话
				String uuid = UUID.randomUUID().toString();
				ConfigUtil.T_SET.add(uuid);
				session.setAttribute("isLogin", uuid);
				//放行请求
				chain.doFilter(request, response);
				return;
			}
		}
		//没有局部会话，重定向到统一认证中心，检查是否已经在其他系统登录过
		String redirectUrl = req.getServletPath();
		String urlString = ConfigUtil.CHECKGETTICKETURL+"?redirectUrl="+ConfigUtil.MYURL+redirectUrl;
		System.out.println("客户端1去认证中心跳转地址:"+urlString);
		resp.sendRedirect(urlString);
		


	}

}
